package com.igeek.ch02.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;


@WebFilter(filterName = "f1",urlPatterns = "/*",
        initParams = @WebInitParam(name="encode",value = "UTF-8"))
public class EncodeFilter implements Filter {

    private String encode;

    public void init(FilterConfig config){
        System.out.println("EncodeFilter init()初始化");
        encode= config.getInitParameter("encode");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        System.out.println("EncodeFilter doFilter...");

        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)resp;

        request.setCharacterEncoding(encode);

        String uri = request.getRequestURI();

        if(uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith(".jpg") || uri.endsWith(".png")){
            //若请求是静态资源，则直接放行
            chain.doFilter(request, response);
        }else{
            response.setContentType("application/json;charset="+encode);
            //过滤链，会将处理好的请求和响应继续传递下去，有可能达到的是下一个过滤器，也有可能达到目标资源
            chain.doFilter(request, response);
        }



    }

    public void destroy(){
        System.out.println("EncodeFilter destroy()销毁...");
    }

}
